package com.example.pei.ithinklearnt.db.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;


import com.example.pei.ithinklearnt.Config;
import com.example.pei.ithinklearnt.bean.UserInfo;
import com.example.pei.ithinklearnt.db.OrderDBHelper;
import com.example.pei.ithinklearnt.db.NewComment;


import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import cn.bmob.v3.BmobUser;


/**
 * 评论表
 * Created by Pei on 2018/4/15.
 */

public class CommentDaoOrder {


    private static HashMap<String, CommentDaoOrder> daoMap = new HashMap<>();


    private OrderDBHelper ordersDBHelper;

    // 列定义
    private final String[] ORDER_COLUMNS = new String[] {"id", "fromUsername","avactor","content","time","status","bcontent"};

    private CommentDaoOrder(Context context,String uId) {


        String DBName = uId+"_iThinkLearnt.db";
        ordersDBHelper = new OrderDBHelper(context,DBName);
    }

    static public CommentDaoOrder  getInstance(Context context){
        UserInfo user = BmobUser.getCurrentUser( UserInfo.class);
        String loginId=user.getObjectId();
        if(TextUtils.isEmpty(loginId)){
            throw new RuntimeException("you must login.");
        }
        CommentDaoOrder dao = daoMap.get(loginId);
        if (dao == null) {
            dao = new CommentDaoOrder(context,loginId);
            daoMap.put(loginId, dao);
        }
        return dao;
    }


    /**
     * 新增一条新评论数据
     */
    public boolean insertComment(NewComment newcomment){

        String id=newcomment.getId();
        String fromUsername=newcomment.getFromUsername();
        String avactor =newcomment.getAvactor();
        String content=newcomment.getContent();
        String time=newcomment.getStringTime();
        int status=newcomment.getStatus();
        String bcontent=newcomment.getbContent();
        SQLiteDatabase db = null;

        try {
            db = ordersDBHelper.getWritableDatabase();
            db.beginTransaction();

            ContentValues contentValues = new ContentValues();
            contentValues.put(ORDER_COLUMNS[0], id);
            contentValues.put(ORDER_COLUMNS[1], fromUsername);
            contentValues.put(ORDER_COLUMNS[2], avactor);
            contentValues.put(ORDER_COLUMNS[3], content);
            contentValues.put(ORDER_COLUMNS[4], time);
            contentValues.put(ORDER_COLUMNS[5], status);
            contentValues.put(ORDER_COLUMNS[6], bcontent);

            db.insertOrThrow(OrderDBHelper.TABLE_NEWCOMMENT, null, contentValues);

            db.setTransactionSuccessful();
            return true;
        }catch (SQLiteConstraintException e){
            Log.e("CommentDaoOrder", "", e);
        }catch (Exception e){
            Log.e("CommentDaoOrder", "", e);
        }finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }
        return false;
    }

    //查询所有本地的新评论通知(不管是否未读已读)
    public ArrayList<NewComment> loadAllNewComments(){
        SQLiteDatabase db = null;
        Cursor cursor = null;
        ArrayList<NewComment> commentsArrayList = new ArrayList<>();

        try {
            db = ordersDBHelper.getReadableDatabase();
            //查询 _comments 表所有数据
            cursor = db.query(OrderDBHelper.TABLE_NEWCOMMENT,null,null,null,null,null,null);

            //遍历游标
            for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()) {
                NewComment comment = new NewComment();
                comment.setId(cursor.getString(cursor. getColumnIndex(ORDER_COLUMNS[0])));
                comment.setFromUsername(cursor.getString(cursor.getColumnIndex(ORDER_COLUMNS[1])));
                comment.setAvactor(cursor.getString(cursor.getColumnIndex(ORDER_COLUMNS[2])));
                comment.setContent(cursor.getString(cursor.getColumnIndex(ORDER_COLUMNS[3])));
                comment.setStringTime(cursor.getString(cursor.getColumnIndex(ORDER_COLUMNS[4])));
                comment.setStatus(cursor.getInt(cursor.getColumnIndex(ORDER_COLUMNS[5])));
                comment.setbContent(cursor.getString(cursor.getColumnIndex(ORDER_COLUMNS[6])));
                commentsArrayList.add(comment);
            }
            //倒序排列一下
            Collections.reverse(commentsArrayList);
        }
        catch (Exception e) {
            // Log.e(TAG, "", e);
        }
        finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }

        return commentsArrayList;
    }

    //获取所有未读的回复的数量
    public int getNewCommentCount(){
        int count=0;
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = ordersDBHelper.getReadableDatabase();
            cursor = db.query(OrderDBHelper.TABLE_NEWCOMMENT,
                    new String[]{"COUNT(*)"},
                    ORDER_COLUMNS[5]+"= ? ",
                    new String[] {String.valueOf(Config.STATUS_VERIFY_NONE)},
                    null, null, null);

            if (cursor.moveToFirst()) {
                count = cursor.getInt(0);
            }
        }
        catch (Exception e) {
             Log.e("CommentDaoOrder", "", e);
        }
        finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }

        return count;
    }

    //获取所有未读的回复
    public ArrayList<NewComment> getNoVerifyNewComment(){
        ArrayList<NewComment> result=new ArrayList<>();

        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = ordersDBHelper.getReadableDatabase();
            cursor = db.query(OrderDBHelper.TABLE_NEWCOMMENT,
                    null,
                    ORDER_COLUMNS[5]+"= ? ",
                    new String[] {String.valueOf(Config.STATUS_VERIFY_NONE)},
                    null, null, null);

            //遍历游标
            for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()) {
                NewComment comment = new NewComment();
                comment.setId(cursor.getString(cursor. getColumnIndex(ORDER_COLUMNS[0])));
                comment.setFromUsername(cursor.getString(cursor.getColumnIndex(ORDER_COLUMNS[1])));
                comment.setAvactor(cursor.getString(cursor.getColumnIndex(ORDER_COLUMNS[2])));
                comment.setContent(cursor.getString(cursor.getColumnIndex(ORDER_COLUMNS[3])));
                comment.setStringTime(cursor.getString(cursor.getColumnIndex(ORDER_COLUMNS[4])));
                comment.setStatus(cursor.getInt(cursor.getColumnIndex(ORDER_COLUMNS[5])));
                comment.setbContent(cursor.getString(cursor.getColumnIndex(ORDER_COLUMNS[6])));
                result.add(comment);
            }
        }
        catch (Exception e) {
            Log.e("CommentDaoOrder", "", e);
        }
        finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }
        return result;
    }

    //批量更新所有未读回复变成已读
    public void updateBatchStatusReaded(){
        ArrayList<NewComment> unReaded=getNoVerifyNewComment();
        if(unReaded!=null && unReaded.size()>0){

            SQLiteDatabase db = null;
            try {
                db = ordersDBHelper.getWritableDatabase();
                db.beginTransaction();

                ContentValues value = new ContentValues();
                value.put(ORDER_COLUMNS[5],Config.STATUS_VERIFY_READED);
                for (int i=0;i<unReaded.size();i++) {
                    db.update(OrderDBHelper.TABLE_NEWCOMMENT, value, "id=?", new String[]{unReaded.get(i).getId()});
                }
                db.setTransactionSuccessful();
            }
            catch (SQLiteConstraintException e){
                Log.e("CommentDaoOrder", "", e);
            }catch (Exception e){
                Log.e("CommentDaoOrder", "", e);
            }finally {
                if (db != null) {
                    db.endTransaction();
                    db.close();
                }
            }
        }
    }

    //批量更新所有回复变成删除  表示这个会话不会再出现除非有新的回复通知
    public void updateBatchStatusDeleted(){
        ArrayList<NewComment> unReaded=loadAllNewComments();
        if(unReaded!=null && unReaded.size()>0){

            SQLiteDatabase db = null;
            try {
                db = ordersDBHelper.getWritableDatabase();
                db.beginTransaction();

                ContentValues value = new ContentValues();
                value.put(ORDER_COLUMNS[5],Config.STATUS_DELETED);
                for (int i=0;i<unReaded.size();i++) {
                    db.update(OrderDBHelper.TABLE_NEWCOMMENT, value, "id=?", new String[]{unReaded.get(i).getId()});
                }
                db.setTransactionSuccessful();
            }
            catch (SQLiteConstraintException e){
                Log.e("CommentDaoOrder", "", e);
            }catch (Exception e){
                Log.e("CommentDaoOrder", "", e);
            }finally {
                if (db != null) {
                    db.endTransaction();
                    db.close();
                }
            }
        }
    }


    /** 根据id删除数据 */
    public int deleteNewComment(String  id) {
        SQLiteDatabase db = null;
        int count=0;
        try {
            db = ordersDBHelper.getWritableDatabase();
            db.beginTransaction();
            count= db.delete(OrderDBHelper.TABLE_NEWCOMMENT, "id=?", new String[] { id });
            db.setTransactionSuccessful();
        }catch (SQLiteConstraintException e){
            Log.e("CommentDaoOrder", "", e);
        }catch (Exception e){
            Log.e("CommentDaoOrder", "", e);
        }finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }
        return count;
    }

    /**
     * 统计查询  此处查询Country为China的用户总数
     */
    public int isSkillMatched(String matchedUserName,String matchedSkill){
        int count = 0;


        SQLiteDatabase db = null;
        Cursor cursor = null;

        try {
            db = ordersDBHelper.getReadableDatabase();
            cursor = db.query(OrderDBHelper.TABLE_NEWCOMMENT,
                    new String[]{"COUNT(*)"},
                    ORDER_COLUMNS[0]+"= ? and "+ORDER_COLUMNS[1]+" = ? ",
                    new String[] {matchedUserName,matchedSkill},
                    null, null, null);

            if (cursor.moveToFirst()) {
                count = cursor.getInt(0);
            }
        }
        catch (Exception e) {
            // Log.e(TAG, "", e);
        }
        finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }

        return count;
    }


}
